package com.ruoyi.web.filter;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.web.utils.R;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
//注意当前类必须受Spring容器控制
//定义拦截器类，实现HandlerInterceptor接口
public class MyInterceptor implements HandlerInterceptor {
    @Override
    // 原始方法调用前执行的内容
    // 返回值类型可以拦截控制的执行，true放行，false终止
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取session中的数据
        Object employee = request.getSession().getAttribute("employee");
        /**
         * 若为空，不放行，且写会页面指定位置
         */
        if(employee == null){
            R<Object> r = R.error("not login");
            response.getWriter().print(JSON.toJSON(r));
            return false;
        }
        return true;
    }

    @Override
    // 原始方法调用后执行的内容
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");

    }

    @Override
    // 原始方法调用完成执行的内容
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");

    }
}
